# -*- coding: utf-8 -*-
import json, urllib
from urllib import urlencode

# ----------------------------------
# 股票查询调用示例代码 － 聚合数据
# 在线接口文档：http://www.juhe.cn/docs/81
# ----------------------------------

def main():
    # 配置您申请的APPKey
    appkey = "f2fa1e94669f3e30c1286ff7ad33****"

    # 1.股票查询
    request1(appkey, "GET")


# 股票查询
def request1(appkey, m="GET"):
    url = "http://op.juhe.cn/onebox/stock/query"
    params = {
        "key": appkey,  # 应用APPKEY(应用详细页查询)
        "dtype": "json",  # 返回数据的格式,xml或json，默认json
        "stock": "中国铝业",  # 股票名称

    }
    params = urlencode(params)
    if m == "GET":
        f = urllib.urlopen("%s?%s" % (url, params))
    else:
        f = urllib.urlopen(url, params)

    content = f.read()
    res = json.loads(content)
    if res:
        error_code = res["error_code"]
        if error_code == 0:
            # 成功请求
            for result in  res["result"][u'fiveDaysTtendency'][u'p']:
                connect(date1=result[u'date'],volumn1=result[u'volumn'],price1=float(result[u'price']),rise1=result[u'rise'],time1=result[u'time'])
        else:
            print "%s:%s" % (res["error_code"], res["reason"])
    else:
        print "request API error"


if __name__=="__main__":
    main()
